package com.cao.controller;

import com.cao.pojo.Books;
import com.cao.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * @Author: huahua
 * @Date: 2020-12-14 15:04
 */
@Controller
@RequestMapping("/book")
public class BookController {

    //controller层调service层

    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;

    //查询全部书籍并展示在页面
    @RequestMapping("/list")
    public String list(Model model) {
        List<Books> books = bookService.queryBookList();
        model.addAttribute("books", books);
        return "list";
    }

    /**
     * 跳转到添加书籍页面
     *
     * @return
     */
    @RequestMapping("/toAddBook")
    public String toAddPage() {
        return "addBook";
    }

    /**
     * 添加书籍操作
     *
     * @param book
     * @return
     */
    @RequestMapping("/addBook")
    public String addBook(Books book) {
        System.out.println("book=>" + book);
        bookService.save(book);
        return "redirect:/book/list";
    }

    /**
     * 跳转到修改书籍页面
     *
     * @return
     */
    @RequestMapping("/toUpdateBook")
    public String toUpdatePage(int id, Model model) {
        Books book = bookService.queryBookById(id);
        model.addAttribute("book", book);
        return "updateBook";
    }

    /**
     * 修改书籍操作
     *
     * @param books
     * @return
     */
    @RequestMapping("/updateBook")
    public String updateBook(Books books) {
        System.out.println("books=>" + books);
        bookService.updateBook(books);
        return "redirect:/book/list";
    }

    /**
     * 删除书籍操作
     * restful风格
     *
     * @param id
     * @return
     */
    @RequestMapping("/delBook/{bookId}")
    public String delBook(@PathVariable("bookId") int id) {
        bookService.delBookById(id);
        return "redirect:/book/list";
    }

    /**
     * 根据姓名查询书籍
     * @param queryBookName
     * @param model
     * @return
     */
    @RequestMapping("/queryBook")
    public String queryBook(String queryBookName, Model model) {
        List<Books> books = bookService.queryBookByName(queryBookName);
        model.addAttribute("books", books);
        return "list";
    }
}
